package com.wind;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;

public class WindConstraintUnique extends WindConstraint {
	
	private static WindConstraint instance = new WindConstraintUnique();
	
	public static WindConstraint getInstance() {
		return instance;
	}
	
	public String getCode() {
		return "wind.datastore.constraint.unique";
	}

	public List<WindConstraintViolation> checkForInsert(WindEntity entity, WindTypeAttribute attribute) {
		return check(entity, attribute);
	}
	
	public List<WindConstraintViolation> checkForUpdate(WindEntity entity, WindTypeAttribute attribute) {
		return check(entity, attribute);
	}
	
	private List<WindConstraintViolation> check(WindEntity entity, WindTypeAttribute attribute) {
		List<WindConstraintViolation> violations = new ArrayList<WindConstraintViolation>();

		String name = attribute.getCode();
		String value = entity.getAttribute(name);
		
		WindQuery query = new WindQuery(entity.getType());
		query.addFilter(name, "=", value);

		List<WindEntity> entities = entity.getType().getService().executeListByQuery(query);
		if(entities.size()>0) {
			WindConstraintViolation violation = new WindConstraintViolation(this, entity, attribute);
			violations.add(violation);
		}
		
		Query query = new Query(this.getType());
		query.addFilter(this.getAttribute(), FilterOperator.EQUAL, value);
		query.addFilter("key", FilterOperator.NOT_EQUAL, entity.getKey());
		PreparedQuery preparedQuery = WindDatastore.service().prepare(query);
		Iterator<Entity> it = preparedQuery.asIterator();
		if(it.hasNext()) {
			violations.add(violation);
		}
		
		return violations;
	}
}
